var containerl = document.getElementById('jsoneditorl');
var containerr = document.getElementById('jsoneditorr');

var optionsr = {
    mode: 'tree',
    modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
    mainMenuBar: true,//菜单栏
    enableTransform: false, //  转换
    enableSort: false,//排序
    onError: function (err) {
        msgError(err.toString())
    },
    onModeChange: function (newMode, oldMode) {

    }
};

var optionsl = {
    mode: 'code',
    //modes: ['code',//可编辑所有内容
    //    'form',//只能修改value值
    //    'text',
    //    'tree',//更改、添加、移动、删除和复制字段和值
    //    'view',
    //    'preview'//可以支持大型JSON文档
    //], // allowed modes
    enableTransform: false, //  转换
    enableSort: false,//排序
    enableRepair: false,
    onError: function (err) {
        //// 主动的修改已触发发生错误时
        msgError(err.toString())
    },
    onModeChange: function (newMode, oldMode) {

    }
};

var editorTitle = $('body').attr('data-title');
switch (editorTitle) {
    case 'jsonsort':
        optionsr = {
            mode: 'code',
            onError: function (err) {
                msgError(err.toString())
            },
            onModeChange: function (newMode, oldMode) {

            }
        };
        optionsl = {
            mode: 'code',
            onError: function (err) {
                msgError(err.toString())
            },
            onModeChange: function (newMode, oldMode) {

            }
        };
        break;
    default:
        break;
}

var json = {
    "array": [1, 2, 3],
    "boolean": true,
    "null": null,
    "number": 123,
    "object": { "a": "b", "c": "d" },
    "string": "Hello World"
};

var editorr = new JSONEditor(containerr, optionsr);
var editorl = new JSONEditor(containerl, optionsl, json);

$('#toTree').click(function () {
    editorr.set(editorl.get())
});
$('#toCode').click(function () {
    editorl.set(editorr.get())
});

// Save a JSON document
$('#saveToDiskl').click(function () {
    if (!editorl.getText()) {
        msgError('暂无数据可以保存');
        return
    }
    // Save Dialog
    var fname = window.prompt("Save as...");

    // Check json extension in file name
    if (fname != null) {
        if (fname && fname.indexOf(".") === -1) {
            fname = fname + ".json"
        } else {
            fname = 'json.json';
            if (fname.split('.').pop().toLowerCase() === "json") {
                // Nothing to do
            } else {
                fname = fname.split('.')[0] + ".json"
            }
        }
        var blob = new Blob([editorl.getText()], { type: 'application/json;charset=utf-8' })
        saveAs(blob, fname)
    }
});
$('#saveToDiskr').click(function () {
    if (!editorr.getText()) {
        msgError('暂无数据可以保存');
        return
    }
    // Save Dialog
    var fname = window.prompt("Save as...");

    // Check json extension in file name
    if (fname != null) {
        if (fname && fname.indexOf(".") === -1) {
            fname = fname + ".json"
        } else {
            fname = 'json.json';
            if (fname.split('.').pop().toLowerCase() === "json") {
                // Nothing to do
            } else {
                fname = fname.split('.')[0] + ".json"
            }
        }
        var blob = new Blob([editorr.getText()], { type: 'application/json;charset=utf-8' })
        saveAs(blob, fname)
    }
});

// copy
//复制
new ClipboardJS('#copyRJson', {
    text: function (trigger) {
        if (editorr.getText()) {
            msgSuccess('复制成功');
            return editorr.getText();
        } else {
            return false
        }
    }
});
new ClipboardJS('#copyLJson', {
    text: function (trigger) {
        if (editorl.getText()) {
            msgSuccess('复制成功');
            return editorl.getText();
        } else {
            return false
        }
    }
});

// 拖动增加和缩减编辑器的宽度
var editorrWidth;
var editorlWidth;
$('#drag').draggable({
    container: '#jsoneditor',
    move: false,
    before: function () {
        editorrWidth = $('#jsoneditorr').innerWidth();
        editorlWidth = $('#jsoneditorl').innerWidth();
    },
    drag: function (e) {
        var lwidth = editorlWidth + e.offset.x;
        var rwidth = editorrWidth - e.offset.x;
        if (lwidth <= 50) {
            $('#drag').draggable('destroy');
            $('#jsoneditorl').hide();
            $('#splitter').hide();
            $('#lEditorArrow').show();
            rwidth = $('#jsoneditor').innerWidth() - 50;
        } else {
            $('#jsoneditorl').width(lwidth)
        }
        if (rwidth <= 50) {
            $('#drag').draggable('destroy');
            $('#jsoneditorr').hide();
            $('#splitter').hide();
            $('#rEditorArrow').show();
            $('#jsoneditorl').width($('#jsoneditor').innerWidth() - 50)
        } else {
            $('#jsoneditorr').width(rwidth)
        }
    },
    finish: function (e) {
    }
});
$('#lEditorArrow').click(function () {
    $('#jsoneditorl').show();
    $('#splitter').show();
    $('#lEditorArrow').hide();
    $('#jsoneditorl').width(60);
    $('#jsoneditorr').width($('#jsoneditor').innerWidth() - 120);
    $('#drag').draggable({
        container: '#jsoneditor',
        move: false,
        before: function () {
            editorrWidth = $('#jsoneditorr').innerWidth();
            editorlWidth = $('#jsoneditorl').innerWidth();
        },
        drag: function (e) {
            var lwidth = editorlWidth + e.offset.x;
            var rwidth = editorrWidth - e.offset.x;
            if (lwidth <= 50) {
                $('#drag').draggable('destroy');
                $('#jsoneditorl').hide();
                $('#splitter').hide();
                $('#lEditorArrow').show();
                rwidth = $('#jsoneditor').innerWidth() - 50;
            } else {
                $('#jsoneditorl').width(lwidth)
            }
            if (rwidth <= 50) {
                $('#drag').draggable('destroy');
                $('#jsoneditorr').hide();
                $('#splitter').hide();
                $('#rEditorArrow').show();
                $('#jsoneditorl').width($('#jsoneditor').innerWidth() - 50)
            } else {
                $('#jsoneditorr').width(rwidth)
            }
        },
        finish: function (e) {
        }
    });
});
$('#rEditorArrow').click(function () {
    $('#jsoneditorr').show();
    $('#splitter').show();
    $('#rEditorArrow').hide();
    $('#jsoneditorr').width(60);
    $('#jsoneditorl').width($('#jsoneditor').innerWidth() - 120);
    $('#drag').draggable({
        container: '#jsoneditor',
        move: false,
        before: function () {
            editorrWidth = $('#jsoneditorr').innerWidth();
            editorlWidth = $('#jsoneditorl').innerWidth();
        },
        drag: function (e) {
            var lwidth = editorlWidth + e.offset.x;
            var rwidth = editorrWidth - e.offset.x;
            if (lwidth <= 50) {
                $('#drag').draggable('destroy');
                $('#jsoneditorl').hide();
                $('#splitter').hide();
                $('#lEditorArrow').show();
                rwidth = $('#jsoneditor').innerWidth() - 50;
            } else {
                $('#jsoneditorl').width(lwidth)
            }
            if (rwidth <= 50) {
                $('#drag').draggable('destroy');
                $('#jsoneditorr').hide();
                $('#splitter').hide();
                $('#rEditorArrow').show();
                $('#jsoneditorl').width($('#jsoneditor').innerWidth() - 50)
            } else {
                $('#jsoneditorr').width(rwidth)
            }
        },
        finish: function (e) {
        }
    });
});

var editorHeight;
$('#resizeJsonEditor').draggable({
    container: '#jsoneditor',
    move: false,
    before: function () {
        editorHeight = $('#jsoneditor').innerHeight();
    },
    drag: function (e) {
        $('#jsoneditor').height((e.offset.y + editorHeight) > 390 ? e.offset.y + editorHeight : 390)
    },
    finish: function (e) {
    }
});

//json排序
function convert(a) {
    try {
        var arr = jsonsort(editorl.get(), a);
        editorr.set(arr);
    } catch (e) {
        return false;
    }
}

// if(window.top.location.host != "www.bejson.com") {
//     window.top.location = "http://www.bejson.com/json/jsonsort/";
// }


function jsonsort(jsonObj, a) {
    var vtype = Object.prototype.toString.call(jsonObj);
    var m = {};
    if (vtype === "[object Object]") {
        var arr = [];
        for (var key in jsonObj) {
            arr.push(key)
        }
        arr.sort();
        if (a != 1) {
            arr.reverse();
        }
        for (var key in arr) {
            key = arr[key];
            var jsonValue = jsonObj[key];
            m[key] = jsonsort(jsonValue, a);
        }
        return m;
    } else if (vtype === "[object Array]") {
        var arr1 = [];
        var vtype = Object.prototype.toString.call(jsonObj[0]);
        if (vtype === "[object String]" || vtype === "[object Number]") {
            jsonObj.sort();
            if (a != 1) {
                jsonObj.reverse();
            }
            return jsonObj;
        } else {
            for (var i = 0; i < jsonObj.length; i++) {
                arr1.push(jsonsort(jsonObj[i], a));
            }
            return arr1;
        }
    } else {
        m = jsonObj;
        return m;
    }
}

$('#ascendingOrder').click(function () {
    convert(1)
});
$('#descendingOrder').click(function () {
    convert(2)
});
$('#clearResult').click(function () {
    editorr.set({});
});